package com.atguigu.gmall.item.redissionTest;

import jdk.nashorn.internal.ir.CallNode;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@RestController
public class RedissionTest {

    @Autowired
    StringRedisTemplate redisTemplate;
    //本地锁分布式下不要用
    //Lock lock=new ReentrantLock();
    /**
     * 普通并发
     * @return
     */
    @GetMapping("/incre/number")
    public String increNumber(){
        System.out.println("处理请求.....");
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "v", 10, TimeUnit.SECONDS);
        while (!lock){
            lock=redisTemplate.opsForValue().setIfAbsent("lock", "v", 10, TimeUnit.SECONDS);
        }

        //lock.lock();
        String result = redisTemplate.opsForValue().get("numberhaha");
        int i = Integer.parseInt(result);
        i++;
        redisTemplate.opsForValue().set("numberhaha", i+"");
        //lock.unlock();
        //删除锁
        redisTemplate.delete("lock");
        return "ok";

    }
}
